package com.imtimmy.android.pda;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.imtimmy.android.pda.ColorPickerDialog.OnColorChangedListener;

public class NewActivity extends Activity {
	private EditText editText_Title;
	private EditText editText_Content;
	private Button btn_Date;
	private Button btn_Time;
	private Button btn_Save;
	private Button btn_Cancel;
	private ImageButton imageBtn_TakeImage;
	private ImageButton imageBtn_RecordVoice;
	private ImageView imageView_Image;
	private TextView tv_Timer;
	private Button btn_colorPicker;

	private AlertDialog dialog_RecordingVoice;
	private MediaRecorder mRecorder;
	// private AudioRecorder mAudioRecorder;
	private long mRecordingStart = 0;
	private int mRecordingTimer = 0;
	private Timer recordingTimer;
	private TimerTask doRecordingTimer;
	private Handler handler;
	private boolean mRecording = false;

	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;
	static final int COLOR_DIALOG_ID = 2;

	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;
	private String sImagePath = "";
	private String sSoundPath = "";
	private int mColor = 0xbbffffff;

	private int mPositionInList = -1;
	private int mId;

	private AlarmManager alarmManager;
	private Context context = this;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_activity);

		editText_Title = (EditText) findViewById(R.id.editText_Title);
		editText_Content = (EditText) findViewById(R.id.editText_Content);
		btn_Date = (Button) findViewById(R.id.btn_Date_newactivity);
		btn_Time = (Button) findViewById(R.id.btn_Time_newactivity);
		btn_Save = (Button) findViewById(R.id.btn_Save_newactivity);
		btn_Cancel = (Button) findViewById(R.id.btn_Cancel_newactivity);
		imageBtn_TakeImage = (ImageButton) findViewById(R.id.imageButton_TakeImage);
		imageBtn_RecordVoice = (ImageButton) findViewById(R.id.ImageButton_RecordAudio);
		imageView_Image = (ImageView) findViewById(R.id.imageView_Pic);
		btn_colorPicker = (Button) findViewById(R.id.btn_colorPicker);

		btn_Save.setOnClickListener(btn_SaveOnClickListener);
		btn_Cancel.setOnClickListener(btn_CancelOnClickListener);
		btn_Date.setOnClickListener(btn_DateOnClickListener);
		btn_Time.setOnClickListener(btn_TimeOnClickListener);
		btn_colorPicker.setOnClickListener(btn_colorPickerOnClickListener);
		imageBtn_TakeImage
				.setOnClickListener(imageBtn_TakeImageOnClickListener);
		imageBtn_RecordVoice
				.setOnClickListener(imageBtn_RecordVoiceOnClickListener);
		imageView_Image.setOnClickListener(imageView_ImageOnClickListener);

		// dialog_RecordingVoice
		Resources resources = getResources();

		AlertDialog.Builder ab = new AlertDialog.Builder(this);
		View view = getLayoutInflater().inflate(R.layout.record_voice_dialog,
				null);
		ab.setView(view);

		ab.setTitle(resources.getString(R.string.dialog_title_recording_voice))
				// 设置标题
				.setMessage(
						resources
								.getString(R.string.dialog_description_click_record_to_start))
				// 设置对话框显示内容
				.setPositiveButton(resources.getString(R.string.btn_record),
						btn_StartRecordClick)
				.setNeutralButton(resources.getString(R.string.btn_play),
						btn_PlayRecordClick)
				.setNegativeButton(resources.getString(R.string.btn_quit),
						btn_StopRecordClick);

		dialog_RecordingVoice = ab.create();

		tv_Timer = (TextView) view.findViewById(R.id.tv_RecordingTimer);

		handler = new Handler();
		Log.e("create", "create");

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			mPositionInList = intent.getIntExtra("position", 0);

			int nId = bundle.getInt(DatabaseHelper.COLUMN_ID);
			Long lDate = bundle.getLong(DatabaseHelper.COLUMN_DATE);
			String sTitle = bundle.getString(DatabaseHelper.COLUMN_TITLE);
			String sContent = bundle.getString(DatabaseHelper.COLUMN_CONTENT);
			sImagePath = bundle.getString(DatabaseHelper.COLUMN_IMAGE);
			Log.i("create", sImagePath);
			sSoundPath = bundle.getString(DatabaseHelper.COLUMN_SOUND);
			mColor = bundle.getInt(DatabaseHelper.COLUMN_COLOR);
			btn_colorPicker.setBackgroundColor(mColor);

			Date date = new Date(lDate);
			mId = nId;
			mYear = date.getYear() + 1900;
			mMonth = date.getMonth();
			mDay = date.getDate();
			mHour = date.getHours();
			mMinute = date.getMinutes();
			updateDisplay();
			editText_Title.setText(sTitle);
			editText_Content.setText(sContent);
			if (sImagePath.length() > 0) {
				Drawable image = Drawable.createFromPath(sImagePath);
				imageView_Image.setImageDrawable(image);
			}

		} else {
			final Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
			mHour = c.get(Calendar.HOUR_OF_DAY);
			mMinute = c.get(Calendar.MINUTE);
			updateDisplay();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void updateDisplay() {
		btn_Date.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mYear).append("-").append(mMonth + 1).append("-")
				.append(mDay).append(" "));
		btn_Time.setText(new StringBuilder().append(pad(mHour)).append(":")
				.append(pad(mMinute)));
	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplay();
		}
	};

	private OnClickListener btn_SaveOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			int nId = -1;
			if (mPositionInList == -1) {
				nId = getIdForNewActivity();
				setIdForNewActivity(nId + 1);
			} else {
				nId = mId;
			}

			Date date = new Date(mYear - 1900, mMonth, mDay, mHour, mMinute, 0);
			Long lDate = date.getTime();
			// Log.e("create", "event: " + String.valueOf(lDate));
			// Log.e("create", "currt: " +
			// String.valueOf(System.currentTimeMillis()));
			String sTitle = editText_Title.getText().toString();
			String sContent = editText_Content.getText().toString();

			Bundle bundle = new Bundle();
			bundle.putInt(DatabaseHelper.COLUMN_ID, nId);
			bundle.putLong(DatabaseHelper.COLUMN_DATE, lDate);
			bundle.putString(DatabaseHelper.COLUMN_TITLE, sTitle);
			bundle.putString(DatabaseHelper.COLUMN_CONTENT, sContent);
			bundle.putString(DatabaseHelper.COLUMN_IMAGE, sImagePath);
			bundle.putString(DatabaseHelper.COLUMN_SOUND, sSoundPath);
			bundle.putInt(DatabaseHelper.COLUMN_COLOR, mColor);

//			Intent intent = new Intent();
//			intent.putExtras(bundle);
//			intent.putExtra("position", mPositionInList);
//
//			setResult(RESULT_OK, intent);

			KeepPath(Global.KEY_IMAGEPATH, "");
			KeepPath(Global.KEY_SOUNDPATH, "");

			ActivityInfo aInfo = Global.getActivityInfo(bundle);
			if(mPositionInList==-1){
				Global.insertData(aInfo,context);
				Global.activityInfos.add(0, aInfo);
			}
			else{
				Global.updateData(aInfo,context);
				Global.activityInfos.set(mPositionInList, aInfo);
			}
			setAlarmEvent(bundle);
			
			finish();

		}
	};

	private void setAlarmEvent(Bundle bundle) {
		Intent alarmIntent = new Intent(this, alarmReceiver.class);

		alarmIntent.putExtras(bundle);
		int nId = bundle.getInt(DatabaseHelper.COLUMN_ID);
		long lDate = bundle.getLong(DatabaseHelper.COLUMN_DATE);
		Date date = new Date(lDate);
		date.setYear(date.getYear() - 1900);
		// lDate = date.getTime();

		PendingIntent sender = PendingIntent.getBroadcast(this, nId,
				alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

		alarmManager.set(AlarmManager.RTC_WAKEUP, lDate, sender);
		// Log.e("create", "event: " + String.valueOf(lDate));
		// Log.e("create", "currt: " +
		// String.valueOf(System.currentTimeMillis()));

	}
	
	private void cancelAlarmEvent(Bundle bundle) {
		Intent alarmIntent = new Intent(this, alarmReceiver.class);
		alarmIntent.putExtras(bundle);
		int nId = bundle.getInt(DatabaseHelper.COLUMN_ID);
		PendingIntent sender = PendingIntent.getBroadcast(this, nId,
				alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
	}
	
	private OnClickListener btn_CancelOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (mPositionInList == -1) {
				File file = new File(sImagePath);
				if (file.exists())
					file.delete();
				file = new File(sSoundPath);
				if (file.exists())
					file.delete();
			}

			setResult(RESULT_CANCELED);

			KeepPath(Global.KEY_IMAGEPATH, "");
			KeepPath(Global.KEY_SOUNDPATH, "");

			finish();

		}
	};

	private OnClickListener btn_DateOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(DATE_DIALOG_ID);

		}
	};

	private OnClickListener btn_TimeOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(TIME_DIALOG_ID);
		}
	};

	private OnClickListener btn_colorPickerOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(COLOR_DIALOG_ID);
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					false);
		case COLOR_DIALOG_ID:
			OnColorChangedListener listener = new OnColorChangedListener() {

				@Override
				public void colorChanged(int color) {
					// TODO Auto-generated method stub
					mColor = color;
				}
			};
			return new ColorPickerDialog(this, listener, mColor) {

				@Override
				public void dismiss() {
					btn_colorPicker.setBackgroundColor(mColor);
					super.dismiss();
				}

			};
		}

		return null;
	}

	private OnClickListener imageBtn_TakeImageOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			String strImgPath = Environment.getExternalStorageDirectory()
					.toString() + "/PDA/images/";// 存放照片的文件夹
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date()) + ".jpg";// 照片命名
			File out = new File(strImgPath);
			if (!out.exists()) {
				out.mkdirs();
			}
			out = new File(strImgPath, fileName);
			strImgPath = strImgPath + fileName;// 该照片的绝对路径
			sImagePath = strImgPath;
			KeepPath(Global.KEY_IMAGEPATH, strImgPath);
			Log.i("ActivityResult", strImgPath);
			Uri uri = Uri.fromFile(out);
			it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			it.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(it, Global.REQUEST_ID_TAKEIMAGE);
		}
	};

	private OnClickListener imageBtn_RecordVoiceOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			dialog_RecordingVoice.show();
			if (sSoundPath.length() > 0) {
				dialog_RecordingVoice
						.getButton(DialogInterface.BUTTON_POSITIVE)
						.setText(
								getResources().getString(R.string.btn_rerecord));
				dialog_RecordingVoice.getButton(DialogInterface.BUTTON_NEUTRAL)
						.setEnabled(true);
			} else {
				dialog_RecordingVoice
						.getButton(DialogInterface.BUTTON_POSITIVE).setText(
								getResources().getString(R.string.btn_record));
				dialog_RecordingVoice.getButton(DialogInterface.BUTTON_NEUTRAL)
						.setEnabled(false);
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i("Result", "NewActivity called");
		String strImgPath = "";
		if (requestCode == Global.REQUEST_ID_TAKEIMAGE) {
			switch (resultCode) {
			case RESULT_OK:
				if (sImagePath.length() > 0) {
					File file = new File(sImagePath);
					if (file.exists())
						file.delete();
				}
				strImgPath = GetPath(Global.KEY_IMAGEPATH);
				sImagePath = strImgPath;
				break;

			case RESULT_CANCELED:
				strImgPath = sImagePath;
				break;
			default:

				break;
			}
			Drawable image = getResources().getDrawable(R.drawable.no_pic);
			if (strImgPath.length() > 0) {
				image = Drawable.createFromPath(strImgPath);
			}
			imageView_Image.setImageDrawable(image);

		} else if (requestCode == Global.REQUEST_ID_RECORDVOICE) {
			switch (resultCode) {
			case RESULT_OK:

				break;

			default:
				break;
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void KeepPath(String key, String value) {
		SharedPreferences sPreferences = getSharedPreferences(
				Global.PREFERENCES, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sPreferences.edit();
		editor.putString(key, value);
		editor.commit();
		Log.i("ActivityResult", "KeepPath: " + value);
	}

	private String GetPath(String key) {
		SharedPreferences sPreferences = getSharedPreferences(
				Global.PREFERENCES, Activity.MODE_PRIVATE);
		return sPreferences.getString(key, "");

	}

	private int getIdForNewActivity() {
		SharedPreferences sPreferences = getSharedPreferences(
				Global.PREFERENCES, Activity.MODE_PRIVATE);
		return sPreferences.getInt("id_for_activity", 0);
	}

	private void setIdForNewActivity(int newId) {
		SharedPreferences sPreferences = getSharedPreferences(
				Global.PREFERENCES, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sPreferences.edit();
		editor.putInt("id_for_activity", newId);
		editor.commit();
	}

	private OnClickListener imageView_ImageOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (sImagePath.length() > 0) {
				File file = new File(sImagePath);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				Uri uri = Uri.fromFile(file);
				intent.setDataAndType(uri, "image/*");
				startActivity(intent);
			}
		}
	};

	private void startRecordVoice() {
		if (mRecorder == null) {
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			// mRecorder.setMaxDuration(1000);

			String strAudioPath = Environment.getExternalStorageDirectory()
					.toString() + "/PDA/voices/";
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date()) + ".3gp";
			File out = new File(strAudioPath);
			if (!out.exists()) {
				out.mkdirs();
			}
			out = new File(strAudioPath, fileName);
			strAudioPath = strAudioPath + fileName;
			sSoundPath = strAudioPath;
			KeepPath(Global.KEY_SOUNDPATH, strAudioPath);

			mRecorder.setOutputFile(strAudioPath);
			mRecorder.setOnErrorListener(errorListener);
			mRecorder.setOnInfoListener(infoListener);
			try {
				mRecorder.prepare();
				mRecorder.start();
			} catch (IllegalStateException e) {
				Log.e("MediaRecorder",e.toString());
				e.printStackTrace();
			} catch (IOException e) {
				Log.e("MediaRecorder",e.toString());
				e.printStackTrace();
			}

			doRecordingTimer = new keepTimeOfRecording();
			recordingTimer = new Timer("recordingTimer");
			mRecordingTimer = 0;
			mRecordingStart = System.currentTimeMillis();
			recordingTimer.scheduleAtFixedRate(doRecordingTimer, 0, 1000);

		}
	}

	private void stopRecordVoice() {
		if (mRecorder != null) {
			mRecorder.stop();
			mRecorder.reset();
			mRecorder.release();
			mRecorder = null;
		}
		if (recordingTimer != null) {
			while (doRecordingTimer.cancel())
				;
			recordingTimer.cancel();
		}
	}

	private void playRecordVoice(String filePath) {
		if (filePath.length() > 0) {
			File file = new File(filePath);
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setAction(Intent.ACTION_VIEW);
			// intent.setDataAndType(Uri.fromFile(file), getMIMEType(file));
			intent.setDataAndType(Uri.fromFile(file), "audio/*");
			startActivity(intent);
		}

	}

	private String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		/* 后缀名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 格式 */
		if (end.equals("amr") || end.equals("m4a") || end.equals("mp3")
				|| end.equals("mid") || end.equals("xmf") || end.equals("ogg")
				|| end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else {
			type = "*";
		}
		type += "/*";
		return type;
	}

	private DialogInterface.OnClickListener btn_StartRecordClick = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			//
			if (!mRecording) {
				if (sSoundPath.length() > 0) {
					File file = new File(sSoundPath);
					if (file.exists())
						file.delete();
				}
				startRecordVoice();
				// mAudioRecorder.startRecording();

				dialog_RecordingVoice.getButton(AlertDialog.BUTTON_NEUTRAL)
						.setEnabled(false);
				dialog_RecordingVoice.getButton(which).setText(
						getResources().getString(R.string.btn_stop));
			} else {
				stopRecordVoice();
				// mAudioRecorder.stopRecording();
				// if (recordingTimer != null) {
				// while (doRecordingTimer.cancel())
				// ;
				// recordingTimer.cancel();
				// }

				dialog_RecordingVoice.getButton(AlertDialog.BUTTON_NEUTRAL)
						.setEnabled(true);
				dialog_RecordingVoice.getButton(which).setText(
						getResources().getString(R.string.btn_rerecord));
			}
			mRecording = !mRecording;

			try {
				Field field = dialog.getClass().getSuperclass()
						.getDeclaredField("mShowing");
				field.setAccessible(true);
				// 将mShowing变量设为false，表示对话框已关闭
				field.set(dialog, false);
				// dialog.dismiss();

			} catch (Exception e) {

			}

		}

	};

	private DialogInterface.OnClickListener btn_PlayRecordClick = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			playRecordVoice(sSoundPath);

			try {
				Field field = dialog.getClass().getSuperclass()
						.getDeclaredField("mShowing");
				field.setAccessible(true);
				// 将mShowing变量设为false，表示对话框已关闭
				field.set(dialog, false);
				dialog.dismiss();

			} catch (Exception e) {

			}

		}

	};

	private DialogInterface.OnClickListener btn_StopRecordClick = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			//

			try {
				Field field = dialog.getClass().getSuperclass()
						.getDeclaredField("mShowing");
				field.setAccessible(true);
				// 将mShowing变量设为false，表示对话框已关闭
				field.set(dialog, true);
				dialog.dismiss();

			} catch (Exception e) {

			}

		}

	};

	private class keepTimeOfRecording extends TimerTask {

		@Override
		public void run() {

			// mRecordingTimer++;
			mRecordingTimer = (int) (System.currentTimeMillis() - mRecordingStart) / 1000;
			handler.post(doUpdateTimerTextView);

			// tv_Timer.setText(mRecordingTimer);
		}
	};

	private Runnable doUpdateTimerTextView = new Runnable() {

		@Override
		public void run() {
			String timeStr = String.format("%02d:%02d", mRecordingTimer / 60,
					mRecordingTimer % 60);

			// int hour = mRecordingTimer / 3600;
			// int min = mRecordingTimer / 60;
			// int sec = mRecordingTimer % 60;
			// Log.i("TImer", String.format("%2d:%2d:%2d", hour, min, sec));
			tv_Timer.setText(timeStr);
			// tv_Timer.setText(String.valueOf(mRecordingTimer));
		}
	};

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			Log.e("Error: " + what, String.valueOf(extra));
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			Log.e("Error: " + what, String.valueOf(extra));
		}
	};

}
